#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QFile>
#include <QFileDialog>
#include <QMessageBox>
#include <QShortcut>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onCurrentIndexChanged(int)));//改变文档解析方式
    connect(ui->textEdit, &QTextEdit::cursorPositionChanged, this, &Widget::onCursorPositionChanged);

    //添加快捷方式
    QShortcut* shortcutOpen = new QShortcut(QKeySequence(tr("Ctrl+O")), this);
    QShortcut* shortcutSave = new QShortcut(QKeySequence(tr("Ctrl+S")), this);
    QShortcut* shortcutZoomUp = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_Up), this);
    QShortcut* shortcutZoomDown = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_Down), this);
    connect(shortcutOpen, &QShortcut::activated,[=](){
        this->on_BtnOpen_clicked();
    });
    connect(shortcutSave, &QShortcut::activated,[=](){
        this->on_BtnSave_clicked();
    });
    connect(shortcutZoomUp, &QShortcut::activated,[=](){
        this->zoomUp();
    });
    connect(shortcutZoomDown, &QShortcut::activated,[=](){
        this->zoomDown();
    });
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_BtnOpen_clicked()
{
    //弹出文件选择框 filename是路径
    QString filename = QFileDialog::getOpenFileName(this, tr("Open File"), "F:/qtcode/NoteBook/", tr("Text (*.txt)"));

    //清除上次打开的文件内容
    ui->textEdit->clear();

    //打开文件
    file.setFileName(filename);
    if(!file.open(QIODevice::ReadWrite | QIODevice::Text))
    {
        qDebug() << file.OpenError;
    }

    //改变窗口标题
    this->setWindowTitle(filename + " 我的记事本");

    //读取文件内容
    QTextStream in(&file);
    in.setCodec(ui->comboBox->currentText().toStdString().c_str());//以combox的输入框内容格式进行读取
    while(!in.atEnd())
    {
        QString context = in.readLine();
        ui->textEdit->append(context);
    }

    // 连接修改文档内容信号槽
    connect(ui->textEdit, &QTextEdit::textChanged, this, [=](){
        qDebug() << "修改信号已被触发";
        qDebug() << "------------------";
        m_isTextChanged = true;
    });

}

void Widget::on_BtnSave_clicked()
{
    if(!file.isOpen())
    {
        //弹出文件选择框 filename是路径
        QString filename = QFileDialog::getSaveFileName(this, tr("保存文件"), "F:/qtcode/NoteBook/untitled.txt", tr("Text (*.txt)"));

        //打开文件
        file.setFileName(filename);
        if(!file.open(QIODevice::ReadWrite | QIODevice::Text))
        {
            qDebug() << file.OpenError;
        }

        //改变窗口标题
        this->setWindowTitle(filename + " 我的记事本");
    }
    //写入文件
    QTextStream out(&file);
    out.setCodec(ui->comboBox->currentText().toStdString().c_str());
    QString context = ui->textEdit->toPlainText();
    out << context;
    m_isTextChanged = false;
}

void Widget::on_BtnClose_clicked()
{
    if(m_isTextChanged == true)
    {
        int ret = QMessageBox::warning(this ,tr("记事本操作提示："), tr("文件内容已经被修改，需要保存修改内容吗？"),
                                       QMessageBox::Yes | QMessageBox::No);
        switch (ret)
        {
        case QMessageBox::Yes:
            on_BtnSave_clicked();
            break;

        case QMessageBox::No:
            break;

        default:
            break;
        }
        m_isTextChanged = false;
    }
    else if(m_isTextChanged == false)
    {
        ui->textEdit->clear();
        if(file.isOpen())
        {
            file.close();
            this->setWindowTitle("我的记事本");
        }
    }


}

void Widget::onCurrentIndexChanged(int index)
{
    //清空输入栏内容
    ui->textEdit->clear();

    //改变文档读入方式
    if(file.isOpen())
    {
        QTextStream in(&file);
        in.setCodec(ui->comboBox->currentText().toStdString().c_str());

        file.seek(0);//让光标回到第一行原点，因为之前已经读入过文档了，光标到了最后

        while(!in.atEnd())
        {
            QString context = in.readLine();
            ui->textEdit->append(context);
            //不要触发文档内容改变信号
            m_isTextChanged = false;
            qDebug() << "文档内容不算改变";
        }
    }
}

void Widget::onCursorPositionChanged()
{
    //获取光标的位置
    QTextCursor cursor = ui->textEdit->textCursor();
    //获取行和列
    QString blockNumber = QString::number(cursor.blockNumber() + 1);
    QString columnNumber = QString::number(cursor.columnNumber() + 1);
    //文本写入标签
    const QString labelwords = "L:" + blockNumber + ", C:" + columnNumber;
    ui->labelPosition->setText(labelwords);


    //设置当前行的高亮
    QList<QTextEdit::ExtraSelection> extraSelections;
    QTextEdit::ExtraSelection ext;
    //知道当前行
    ext.cursor = ui->textEdit->textCursor();
    //设置高亮颜色
    QBrush qBursh(Qt::yellow);
    ext.format.setBackground(qBursh);
    ext.format.setProperty(QTextFormat::FullWidthSelection, true);
    //设置进入行
    extraSelections.append(ext);
    ui->textEdit->setExtraSelections(extraSelections);
}

void Widget::zoomUp()
{
    //获得textEdit的字体信息
    QFont font = ui->textEdit->font();
    //获得当前字体的大小
    int fontSize = font.pointSize();
    if(fontSize == -1) return;
    //改变字体大小
    int newFontSize = fontSize + 1;
    font.setPointSize(newFontSize);
    ui->textEdit->setFont(font);
}

void Widget::zoomDown()
{
    //获得textEdit的字体信息
    QFont font = ui->textEdit->font();
    //获得当前字体的大小
    int fontSize = font.pointSize();
    if(fontSize == -1) return;
    //改变字体大小
    int newFontSize = fontSize - 1;
    font.setPointSize(newFontSize);
    ui->textEdit->setFont(font);
}
